import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';

class MultiController extends ChangeNotifier {
  int loadTime = 300;

  int loadingStart = 0;

  MultiStateStatus initStatus = MultiStateStatus.loading;

  Widget? loadingWidget;

  Widget? errorWidget;

  Widget? emptyWidget;

  Timer? _timer;

  late BuildContext context;

  MultiController() {
    DateTime now = DateTime.now();
    loadingStart = now.millisecond;
  }

  viewStateChange(MultiStateStatus status) {
    if (status != initStatus) {
      if (initStatus == MultiStateStatus.loading) {
        if (status != MultiStateStatus.loading) {
          DateTime now = DateTime.now();
          int exceedStandardTime = now.millisecond - loadingStart;
          if (exceedStandardTime > loadTime) {
            initStatus = status;
            notifyListeners();
          } else {
            int endTime = loadTime - exceedStandardTime;
            _timer = Timer(Duration(milliseconds: endTime), () {
              initStatus = status;
              notifyListeners();
            });
          }
        } else {
          initStatus = status;
          notifyListeners();
        }
      } else {
        initStatus = status;
        notifyListeners();
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    //在页面回收或滑动复用回收的时候一定要把 timer 清除
    if (_timer != null) {
      if (_timer!.isActive) {
        _timer!.cancel();
        _timer = null;
      }
    }
  }
}
